//
//  ViewController.m
//  NinevehglTest
//
//  Created by 郝建林 on 2016/10/10.
//  Copyright © 2016年 CoolTools. All rights reserved.
//

#import "MainViewController.h"
#import "EulerRotation.h"
#import "QuaternionRotation.h"

@interface MainViewController ()
{
    NGLMesh *mesh;
    NGLCamera *camera;
    id<RotationState> rotation;
    NSDictionary *meshSettings;
    ModelsViewController *modelsVc;
}
@property (weak, nonatomic) IBOutlet UISlider *wSlider;
@property (weak, nonatomic) IBOutlet UISlider *xSlider;
@property (weak, nonatomic) IBOutlet UISlider *ySlider;
@property (weak, nonatomic) IBOutlet UISlider *zSlider;
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet UIButton *centerBtn;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSDictionary *defaultModel = @{@"name": @"Keychain", @"file": @"Keychain.obj"};
    self.navigationItem.title = defaultModel[@"name"];
    //nglGlobalColorFormat(NGLColorFormatRGBA);
    nglGlobalEngine(NGLEngineVersionES2);
    nglGlobalAntialias(NGLAntialias4X);
    nglGlobalFlush();
    meshSettings = @{kNGLMeshCentralizeYes:@YES, kNGLMeshKeyNormalize:@0.5f};
    mesh = [[NGLMesh alloc] initWithFile:defaultModel[@"file"] settings:meshSettings delegate:nil];
    camera = [[NGLCamera alloc] initWithMeshes:mesh, nil];
    rotation = [[QuaternionRotation alloc] init];
    rotation.view = self.view;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)drawView {
    mesh.rotateX = rotation.rx;
    mesh.rotateY = rotation.ry;
    mesh.rotateZ = rotation.rz;
    [camera drawCamera];
}

- (IBAction)reset:(id)sender {
    [rotation reset];
}

- (IBAction)sliderChanged:(id)sender {
    UISlider *slider = (UISlider *)sender;
    [rotation onSliderChanged:slider.tag-SliderTagBase value: slider.value];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"showModels"]) {
        modelsVc = (ModelsViewController*)segue.destinationViewController;
        modelsVc.delegate = self;
    }
}

#pragma mark - delegate methods

- (void)onModelSelected:(NSDictionary *)model {
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationItem.title = model[@"name"];
    NSString *modelFile = model[@"file"];
    mesh = [mesh initWithFile:modelFile settings:meshSettings delegate:nil];
    camera = [camera initWithMeshes:mesh, nil];
}

@end
